import { Button, message, Modal, Tag, Upload, UploadFile, UploadProps } from 'antd';
import * as XLSX from 'xlsx';
const { Dragger } = Upload;

import ProTable from '@ant-design/pro-table';
import { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import type { UploadExcelSaveProps } from './data';
const ChildUploadFileSave: React.FC<UploadExcelSaveProps> = (props, uploadRef) => {
  //   state = {
  //     tableData: [],
  //     tableHeader: [],
  //   };

  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [fields, setFields] = useState([]);
  const [tableData, setTableData] = useState([]);
  const [tableHeader, setTableHeader] = useState([]);

  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  // const [errorStatus, setErrorStatus] = useState(false);
  const props1: UploadProps = {
    onRemove: (file) => {
      const index = fileList.indexOf(file);
      const newFileList = fileList.slice();
      newFileList.splice(index, 1);
      setFileList(newFileList);
    },
    beforeUpload: (file) => {
      setFileList([...fileList, file]);
      return false;
    },
    fileList,
  };


  useEffect(() => {
    setVisible(props.visible);
    const temp = props.tableHeader.filter((item) => item.title !== '操作');
    const tempfields = props.tableHeader
      .filter((item) => item.title !== '操作' && item.dataIndex !== 'index')
      .map((item) => item.dataIndex);
    // props.tableHeader.map((item) => {
    //   label[item.dataIndex] = item.title;
    // });
    if (props.errorStatus) {
      temp.push({
        title: '错误信息',
        width: 120,
        align: 'center',
        dataIndex: 'errorMsg',
        fixed: 'right',
        render: (text, record, _, action) => {
          if (text !== '-') {
            return <Tag color={'red'}>{text}</Tag>;
          }
          // return <Tag color={'red'}>{text}</Tag>;
        },
      });
    }

    setTableHeader(temp || []);
    setFields(tempfields || []);
  }, [props.visible, props.tableHeader, props.errorStatus]);

  useImperativeHandle(uploadRef, () => {
    // return返回的值就可以被父组件获取到,没返回的值就获取不到
    return {
      fileList: fileList,
    };
  });
  //   toReturn = () => {
  //     this.props.close();
  //   };

  //   toSubmit = () => {
  //     const _this = this;
  //     this.props.submit(_this.state.tableData);
  //   };
  const uploadFilesChange = async (file) => {
    // 通过FileReader对象读取文件
    const fileReader = new FileReader();
    // 以二进制方式打开文件
    fileReader.readAsBinaryString(file.file);
    setTableData([]);
    setFileList(file);
    console.log(fileList, "---fileList---");
    // const formData = new FormData();
    // fileList.map((file) => {formData.append('file', file);});
    
    fileReader.onload = (event) => {
      try {
        const { result } = event.target;
        // 以二进制流方式读取得到整份excel表格对象
        const workbook = XLSX.read(result, { type: 'binary' });
        // 存储获取到的数据
        const data = {};
        // 遍历每张工作表进行读取（这里默认只读取第一张表）
        for (const sheet in workbook.Sheets) {
          const tempData = [];
          // esline-disable-next-line
          if (workbook.Sheets.hasOwnProperty(sheet)) {
            const sheet2JSONOpts = {
              header: fields, //给defval赋值为空的字符串
              raw: true,
            };
            data[sheet] = tempData.concat(
              XLSX.utils.sheet_to_json(workbook.Sheets[sheet], sheet2JSONOpts),
            );
          }
        }
        const excelData = data.Sheet1;
        excelData.map((item) => (item.id = (Math.random() * 1000000).toFixed(0)));
        setTableData(excelData.filter((item, index) => index !== 0 && item.driveType != ''));
      } catch (e) {
        // 这里可以抛出文件类型错误不正确的相关提示
        console.log(e);
        message.error('文件类型不正确！');
      }
    };
  };

  return (
    <div>
      <Modal
        width={1000}
        height="93%"
        wrapClassName="modal"
        className="modal-add-content"
        title={props.title}
        okButtonProps={{ loading: loading }}
        visible={visible}
        onCancel={() => {
          props.onCancel();
        }}
        // onOk={async () => {
        //   setLoading(true);
        //   props.onOk();
        //   setLoading(false);
        // }}
        destroyOnClose={true}
        footer={null}
      >
        <Dragger
          name="file"
          accept=".xls,.xlsx"
          maxCount={1}
          beforeUpload={function () {
            return false;
          }}
          onChange={(info) => {
            console.log('---uploadFilesChange--');
            props.onChange(info.file);
            uploadFilesChange(info);
          }}
          showUploadList={false}
        >
          <p className="ant-upload-text">
            <span>点击上传文件</span>
            或者拖拽上传
          </p>
        </Dragger>
        <ProTable
          search={false}
          options={false}
          columns={tableHeader}
          scroll={{ x: 3500, y: 300 }}
          dataSource={tableData}
          style={{ marginTop: '20px' }}
          // recordCreatorProps={{
          //   record: () => {
          //     return {
          //       id: `0${Date.now()}`,
          //     };
          //   },
          // }}
          rowKey="id"
          pagination={false}
        />
        <div style={{ textAlign: 'center', marginTop: '20px' }}>
          <Button
            onClick={() => {
              props.onCancel();
            }}
          >
            返回
          </Button>
          <Button
            onClick={() => {
              const result = props.onCheck(tableData);
              // console.log(result);
              setTableData(result);
            }}
          >
            校验按钮
          </Button>
          <Button
            style={{ marginLeft: '25px' }}
            onClick={async () => {
              setLoading(true);
              props.onOk(tableData, tableHeader);
              setLoading(false);
            }}
            className="addbutton"
            type="primary"
          >
            确认
          </Button>
        </div>
      </Modal>
    </div>
  );
};

const UploadFileSave = forwardRef<unknown, UploadExcelSaveProps>(ChildUploadFileSave);

export default UploadFileSave;
